<?php

namespace App\Middleware;

use Closure;
use Illuminate\Http\Request;
use App\Services\HallDomainService;

class RedirectMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        // 跨域处理
        if ($request->method() === 'OPTIONS') {
            return response("", 204, $this->headers($request));
        }
        $uri = $request->server->get('REQUEST_URI');
        // 默认跳转规则
        if (!preg_match('/^\/v\d+.*/', $uri)) {
            $defaultRoute = config('app.default_route', '/v1');
            return $this->forward($defaultRoute . $uri, $request);
        }
        HallDomainService::getHallID();
        return $next($request)->withHeaders($this->headers($request));
    }

    /**
     * Jump route.
     *
     * @param  string  $uri
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function forward($uri, Request $request)
    {
        $q = $request->query->all();
        $r = $request->request->all();
        $a = $request->attributes->all();
        $c = $request->cookies->all();
        $f = $request->files->all();
        $s = $request->server->all();

        $s['REQUEST_URI'] = $uri;
        if (isset($s['PATH_INFO'])) {
            $s['PATH_INFO'] = $uri;
        }
        $request->initialize($q, $r, $a, $c, $f, $s, $request->getContent());
        return app()->dispatch($request);
    }


    public function headers(Request $request)
    {
        $headers = [
            'Allow' => 'GET, PUT, PATCH, DELETE, HEAD, OPTIONS',
            'Access-Control-Allow-Origin' => $request->server->get('HTTP_ORIGIN'),
            'Access-Control-Allow-Methods' => 'GET, PUT, PATCH, DELETE, HEAD, OPTIONS',
            'Access-Control-Allow-Headers' => 'Authorization, Content-Type',
        ];
        return $headers;
    }
}
